package org.zoomdev.zoom.web.parameter;

import jakarta.servlet.http.HttpServletRequest;
import org.zoomdev.zoom.common.caster.Caster;
import org.zoomdev.zoom.validator.SimpleValidator;
import org.zoomdev.zoom.validator.Validators;
import org.zoomdev.zoom.web.action.ActionContext;

import java.lang.reflect.AnnotatedElement;
import java.lang.reflect.Type;

class ValidatedParameterAdapter implements ParameterAdapterFactory {

    @Override
    public ParameterAdapter createParameterAdapter(String name, Type type, AnnotatedElement element) {
        Object defaultValue = Validators.getDefaultValue(type, element);
        SimpleValidator validator = Validators.createValidator(name, type, element);

        return new ParameterAdapter() {

            @Override
            public Object get(ActionContext context, String name, Type type) {
                HttpServletRequest request = context.getRequest();
                Object value = request.getAttribute(name);

                // Apply default value if exists
                if (value == null && defaultValue != null) {
                    value = defaultValue;
                    request.setAttribute(name, value); // Update request with default value
                    return Caster.toType(value, type);
                }

                // Validate the value if validator exists
                if (validator != null && value != null) {
                    validator.validate(value);
                }

                return Caster.toType(value, type);
            }
        };
    }


}
